package upgrade

import (
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
)

type VersionInfo struct {
	Version     string `json:"version"`
	VersionCode int64  `json:"versionCode"`
	UpdateTime  string `json:"updateTime"`
	Detail      string `json:"detail"`
	DownloadUrl string `json:"downloadUrl"`
	Md5         string `json:"md5"`
}

var info VersionInfo

// CheckVersion 查看版本更新
func CheckVersion(url string, success func(res VersionInfo), fail func(err string)) {
	client := resty.New()
	resp, err := client.R().
		EnableTrace().
		Get(url)
	if err != nil {
		fail("检测更新失败！" + err.Error())
	} else {
		if resp.StatusCode() == 200 && len(resp.Body()) > 0 {
			err = json.Unmarshal(resp.Body(), &info)
			if err != nil {
				fail(err.Error())
			} else {
				success(info)
			}
		} else {
			fail("检测更新失败！code：" + fmt.Sprintf("%v", resp.StatusCode()))
		}
	}
}
